<template>
  <div class="crud-opts">
    <span class="crud-opts-left">
      <!--左侧插槽-->
      <slot name="left"/>
      <el-button
        v-permission="permission.publish"
        class="filter-item"
        size="mini"
        type="info"
        icon="el-icon-refresh-left"
        :disabled="dynamicDisable(crud.selections)"
        @click="back(crud.selections[0])"
      >
        还原
      </el-button>
      <el-button
        v-if="crud.optShow.del"
        slot="reference"
        v-permission="permission.del"
        class="filter-item"
        type="danger"
        icon="el-icon-delete"
        size="mini"
        :loading="crud.delAllLoading"
        :disabled="crud.selections.length === 0"
        @click="toDelete(crud.selections)"
      >
        删除
      </el-button>
      <slot name="right"/>
    </span>
    <el-button-group class="crud-opts-right">
      <el-button
        size="mini"
        plain
        type="info"
        icon="el-icon-search"
        @click="toggleSearch()"
      />
      <el-button
        size="mini"
        icon="el-icon-refresh"
        @click="crud.refresh()"
      />
      <el-popover
        placement="bottom-end"
        width="150"
        trigger="click"
      >
        <el-button
          slot="reference"
          size="mini"
          icon="el-icon-s-grid"
        >
          <i
            class="fa fa-caret-down"
            aria-hidden="true"
          />
        </el-button>
        <el-checkbox
          v-model="allColumnsSelected"
          :indeterminate="allColumnsSelectedIndeterminate"
          @change="handleCheckAllChange"
        >
          全选
        </el-checkbox>
        <el-checkbox
          v-for="item in crud.props.tableColumns"
          :key="item.label"
          v-model="item.visible"
          @change="handleCheckedTableColumnsChange(item)"
        >
          {{ item.label }}
        </el-checkbox>
      </el-popover>
    </el-button-group>
    <el-dialog
      :close-on-click-modal="false"
      :before-close="cancelCU"
      :visible.sync="backFlag"
      append-to-body
      title="发布包还原(*仅支持回退周期脚本文件)"
      width="450px"
    >
      <el-form ref="publishForm" :model="backForm" :rules="backRules" :inline="true" label-width="120px">
        <el-form-item label="还原集群" prop="clusterIds">
          <el-select
            v-model="backForm.clusterIds"
            disabled
            multiple
            placeholder="请选择还原集群"
            class="filter-item"
            style="width: 200px"
          >
            <el-option v-for="item in clusterLists" :key="item.key" :label="item.value" :value="item.key"/>
          </el-select>
        </el-form-item>
        <el-form-item label="还原用户" prop="publishUser">
          <el-input
            v-model="backForm.publishUser"
            disabled
            class="filter-item"
            style="width: 200px"
          />
        </el-form-item>
        <div class="dialog-footer" style="width:100%;text-align: center;margin-top: 20px">
          <el-button @click="cancelCU">关 闭</el-button>
          <el-button type="primary" @click="backSubmitCU">回 退</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import CRUD, { crud } from '@crud/crud'
import clusterSparingApi from '@/api/cluster/clusterSparing'
import scriptPublishTaskApi from '@/api/script/publish/scriptPublishTask'
import scriptPublishVersionApi from '@/api/script/publish/scriptPublishVersion'

export default {
  mixins: [crud()],
  props: {
    permission: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      publishClusterNames: '',
      publishInfo: [],
      backInfo: [],
      allColumnsSelected: true,
      allColumnsSelectedIndeterminate: false,
      publishFlag: false,
      publishForm: {
        clusterIds: []
      },
      clusterLists: [],
      publishRules: {
        clusterIds: [
          { required: true, message: '请选择发布集群', trigger: 'blur' }
        ]
      },
      backFlag: false,
      backForm: {
        clusterIds: []
      },
      backRules: {
        clusterIds: [
          { required: true, message: '请选择还原集群', trigger: 'blur' }
        ],
        publishUser: [
          { required: true, message: '请填写还原用户', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.crud.updateProp('searchToggle', true)
    this.initData()
  },
  methods: {
    initData() {
      clusterSparingApi.findListByPage().then(res => {
        res.records.forEach((array) => {
          this.clusterLists.push({ key: array.id, value: array.clusterName })
        })
      })
    },
    cancelCU() {
      this.publishFlag = false
      this.backFlag = false
    },
    toDelete(datas) {
      this.$confirm(`确认删除选中的${datas.length}条数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.crud.delAllLoading = true
        this.crud.doDelete(datas)
      }).catch(() => {
      })
    },
    publish(data) {
      this.publishInfo = data
      this.publishFlag = true
    },
    dynamicDisable(selections) {
      if (selections.length > 0) {
        const isSelection = selections.length === 1
        const publishStatus = selections[0].publishState === 'PUBLISHED'
        const noFail = selections.every(item => item.publishFail === 0)
        return !isSelection || !publishStatus || !noFail
      } else {
        return true
      }
    },
    back(data) {
      this.backInfo = data
      this.backFlag = true
      this.backForm.clusterIds = data.publishClusterList
      this.backForm.publishUser = data.publishUser
    },
    publishSubmitCU() {
      const data = this.publishInfo
      data.publishClusterIds = this.publishForm.clusterIds.toString()
      // scriptPublishTaskApi.edit(data).then(res => {
      this.$notify({ title: '成功', message: '发布开始', type: 'success' })
      // })
      // 这里替换为version的发布
      scriptPublishVersionApi.publish(data, this.publishForm.clusterIds.toString()).then(info => {
        this.$notify({ title: '成功', message: '发布成功', type: 'success' })
        this.crud.refresh()
      })
      this.publishFlag = false
    },
    backSubmitCU() {
      const publishTaskId = this.backInfo.id
      const clusterIds = this.backForm.clusterIds
      this.$notify({ title: '成功', message: '还原开始', type: 'success' })
      scriptPublishTaskApi.restore(publishTaskId, clusterIds[0]).then(info => {
        this.crud.refresh()
      })
      this.backFlag = false
    },
    handleCheckAllChange(val) {
      if (val === false) {
        this.allColumnsSelected = true
        return
      }
      for (const key in this.crud.props.tableColumns) {
        this.crud.props.tableColumns[key].visible = val
      }
      this.allColumnsSelected = val
      this.allColumnsSelectedIndeterminate = false
    },
    handleCheckedTableColumnsChange(item) {
      let totalCount = 0
      let selectedCount = 0
      for (const key in this.crud.props.tableColumns) {
        ++totalCount
        selectedCount += this.crud.props.tableColumns[key].visible ? 1 : 0
      }
      if (selectedCount === 0) {
        this.crud.notify('请至少选择一列', CRUD.NOTIFICATION_TYPE.WARNING)
        this.$nextTick(function() {
          item.visible = true
        })
        return
      }
      this.allColumnsSelected = selectedCount === totalCount
      this.allColumnsSelectedIndeterminate = selectedCount !== totalCount && selectedCount !== 0
    },
    toggleSearch() {
      this.crud.props.searchToggle = !this.crud.props.searchToggle
    }
  }
}
</script>

<style>
.crud-opts {
  padding: 6px 0;
  display: -webkit-flex;
  display: flex;
  align-items: center;
}

.crud-opts .crud-opts-right {
  margin-left: auto;
}
</style>
